<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Token;
use app\common\model\Trade as TradeModel;
use app\common\model\trade\Log as Tradelog;
use think\Cache;
use app\common\model\User;
use app\common\model\Tokenlog;
use app\common\model\Bank;
use think\Db;
use think\Hook;
use fast\Random;
use think\Paginator;
use app\common\library\Sms as Smslib;
use app\common\library\Ems as Emslib;

class Inout extends Frontend
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $layout = 'layout';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
         Hook::add('check_paypwd', function ($paypwd) use ($auth) {
            if ($auth->getUser()['payplaintext'] != $paypwd) {
                $this->error('安全密码不正确');
            }
        });
        Hook::add('check_pay', function () use ($auth) {

        $trade_pay = config('site.trade_pay');
        $user = $auth->getUser();
        foreach ($trade_pay as $pay) {
            switch ($pay) {
                case 'alipay':
                    if (empty($user->alipay)) {
                        $this->error('未完善支付宝信息');
                    }
                    break;
                case 'wechatwallet':
                    if (empty($user->wechatwallet)) {
                        $this->error('未完善微信信息');
                    }
                    break;
                case 'bank':
                    $bank = new Bank();
                    $banks=$bank->where('status',1)->where('user_id',$auth->id)->order('default desc,id desc')->select();
                    if (empty($banks)) {
                        $this->error('未完善银行卡信息');
                    }
                    break;
                case 'eth':
                    if (empty($user->eth)) {
                        $this->error('未完善钱包地址信息');
                    }
                    break;
                case 'mobile':
                    if (empty($user->mobile)) {
                        $this->error('未完善电话信息');
                    }
                    break;
                case 'email':
                    if (empty($user->email)) {
                        $this->error('未完善邮箱信息');
                    }
                    break;
                default:
                    $this->error('收付款信息错误');
                    break;
            }
        }
        });

        Hook::add('get_userpay',function($user_id){
            // $user = $auth->getUser();
            $user = User::get($user_id);
            // var_dump($user);
            $pay['alipay']='';
            $pay['wechatwallet']='';
            $pay['banks']='';
            $pay['eth']='';
            $pay['mobile']='';
            if (!empty($user->alipay)) {
                $pay['alipay'] = $user->alipay;
            }
            if (!empty($user->wechatwallet)) {
                $pay['wechatwallet'] = $user->wechatwallet;
            }
            if (!empty($user->eth)) {
                $pay['eth'] = $user->eth;
            }
            if (!empty($user->mobile)) {
                $pay['mobile'] = $user->mobile;
            }

            $bank = new Bank();
            $banks=$bank->where('status',1)->where('user_id',$user_id)->where('default',1)->find();

            if (!empty($banks)) {
                $pay['banks'] = $banks;
            }
            return $pay;
        }); 
    }
    /**
     * 获取交易场上 挂卖或挂买订单
     * @param string $action 查询挂卖或挂买  buy or sell
     * @return [type] [description]
     */
    public function getTradeList()
    {
         $url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
         $link=parse_url($url, PHP_URL_PATH);
         $arr=explode('.', $link);
         $arrusd=explode('/', $arr[0]);

        $action =$arrusd[5];
        if (!in_array($action, ['buy','sell'])) {
             $action =$arrusd[7];
            if (!in_array($action, ['buy','sell'])) {
               $this->error('查询异常，buy or sell');
             }
        }
        $trademodel = new TradeModel();
        $trades = $trademodel
            ->where('symbol','USD')
            ->where('tosymbol','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('action',$action)
            ->order('id desc')
            ->paginate(10);
            
       
       return $this->view->fetch('gettradelist',['list'=>$trades,'type'=>$arrusd[5]]);
    }
     /**
     *会员体现接口
     * 
     * @ApiParams   (name="num", type="int", required=true, description="要提现的数量")
     * @ApiParams   (name="paypwd", type="string", required=true, description="安全密码")
     * TODO  如果USD改名成 则这里也要更改
     */
    public function moneyout()
    {       $token = $this->auth->getUserToken();
           $trade_poundage = config('site.trade_poundage');
            // $rate = config('site.trade_exch_rate');
            $yb = db('coin')->where('symbol','USD')->find();
            $fae = db('coin')->where('symbol','FAE')->find();
            $trade_out_poundage = config('site.trade_out_poundage');
            $trade_in_poundage = config('site.trade_in_poundage');

          if ($this->request->isPost()) {
            $num = $this->request->post('num');
            $paypwd = $this->request->post('paypwd','');
            Hook::listen("check_paypwd",$paypwd);
            Hook::listen('check_pay');
            try {
                $token = $this->auth->getUserToken()['USD'];
            } catch (\Exception $e) {
                $token = 0;
            }

            if ($num > $token) {
                $this->error('余额不足');
            }

            $trade_out_min = config('site.trade_out_min');
            $trade_out_multiple = config('site.trade_out_multiple');
            if ($trade_out_min > $num) {
                $this->error(__('至少要'.$trade_out_min));
            }

            if ($num % $trade_out_multiple != 0) {
                $this->error(__('请输入'.$trade_out_multiple.'的倍数'));
            }

            $coin = db('coin')->where('symbol','USD')->field('id,name,symbol,exch_rate,describe')->find();
            $trademodel = new TradeModel();

            $data = [
                'action' => 'sell',
                'user_id'   =>  $this->auth->id,
                'exch_rate' =>  $coin['exch_rate'],
                'num'       =>  $num,
                'surplusnum'        =>  $num,
                'symbol'    =>  'USD',
                'tosymbol'  =>  'USDT',
                'pay'       =>  '$pay'
            ];



            $result = $trademodel->allowField(true)->validate('Trade.add')->save($data);
            // echo $trademodel->getLastSql();die;
            if(false === $result){
                $this->error($trademodel->getError());
            }else{
                User::tokenlog('USD',$this->auth->id,0,-$num,'sell','卖出-提现');
                $trade_out_poundage = config('site.trade_out_poundage');
                User::tokenlog('USD',$this->auth->id,0,-$num*bcdiv($trade_out_poundage, 100,3),'sell_poundage','卖出扣除手续费');
                // TODO user 静态方法 扣除钱包 并写入记录
            }
            $this->success('委托提现成功');
        }
        return $this->view->fetch('',['token'=>$token,'trade_out_poundage'=>$trade_out_poundage,'rate'=>['USD'=>$yb['exch_rate'],'FAE'=>$fae['exch_rate']]]);
    }
    /**
     * 获取我的发布
     * @param string $action 查询挂卖或挂买  buy or sell
     * @return [type] [description]
     */
    public function getmypublish()
    {
        $trademodel = new TradeModel();
        $trades = $trademodel
            ->where('symbol|tosymbol','USDT')
            ->where('user_id',$this->auth->id)
            ->order('id desc')
            ->paginate(10);
         
        return $this->view->fetch('',['list'=>$trades]);
    }
     /**
     * 我的交易订单 提现和充值
     * @ApiParams   (name="action", type="string", required=true, description="买入卖出查询  buy  sell")
     * @ApiParams   (name="type", type="int", required=true, description="0=>等待中（未开始交易）,1=>进行中,2=>已完成，3=>撤销,4=>锁定中,5=>异常")
     * @ApiParams   (name="page", type="int", required=true, description="当前页数")
     * @return [type] [description]
     */
    public function getmyorders()
    {
        // $this->success('返回成功',['list'=>[]]);
        $user_id = $this->auth->id;
        $status =-1;
        $where=[];
        if ($status != -1) {
            $where['status']=$status;
        }
        $tradelog = new Tradelog();
        $orders = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)
            ->where('symbol','USD')->where('tosymbol','USDT')
            ->where($where)
            ->order('id desc')
            ->paginate(10);
         
        return $this->view->fetch('',['list'=>$orders,'user_id'=>$user_id]);
    }
        /**
     * 我的交易详情
     * @ApiParams   (name="id", type="int", required=true, description="匹配订单详情")
     * @return [type] [description]
     */
    public function gettradelog()
    {
        $id =$_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }

        $tradelog = new Tradelog();

        $trade_log = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)->where('id',$id)->find();

        $user_id = $this->auth->id;
        $userpay = Hook::listen("get_userpay",$user_id);
        $trade_log->pay = $userpay[0];


        $step1 =  config('site.trade_dispute_time_step1');
        $step2 =  config('site.trade_dispute_time_step2');

        if ( $trade_log->buy_user_id == $this->auth->id) {
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 0;
            }elseif($trade_log->status == 'affirm' && ($trade_log->updatetime + $step2*60 < time()) ){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }


            $user_id = $trade_log->sell_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];


        }elseif($trade_log->sell_user_id == $this->auth->id){
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 1;
            }elseif($trade_log->status == 'affirm'){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }
            $user_id = $trade_log->buy_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];

        }

        if ($trade_log['sell_user_id']==$this->auth->id) {
            $type=1;
        }else{
            $type=0;
        } 
       
        return $this->view->fetch('',['info'=>$trade_log,'type'=>$type]); 
       
    }
     public function getUserBaseInfo()
    {
        $username = $this->request->request('username');

        $user = \app\common\model\User::where('username', $username)->find();
        // $this->error(__('发送失败 code：002'));
        if (!$user) {
            $this->error(__('会员不存在'));
        }else{
           
          return json_decode($user['mobile']);
        }
    }
    public function upload(){
     
  
        $id =$_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }

        $tradelog = new Tradelog();

        $trade_log = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)->where('id',$id)->find();

        $user_id = $this->auth->id;
        $userpay = Hook::listen("get_userpay",$user_id);
        $trade_log->pay = $userpay[0];


        $step1 =  config('site.trade_dispute_time_step1');
        $step2 =  config('site.trade_dispute_time_step2');

        if ( $trade_log->buy_user_id == $this->auth->id) {
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 0;
            }elseif($trade_log->status == 'affirm' && ($trade_log->updatetime + $step2*60 < time()) ){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }


            $user_id = $trade_log->sell_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];


        }elseif($trade_log->sell_user_id == $this->auth->id){
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 1;
            }elseif($trade_log->status == 'affirm'){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }
            $user_id = $trade_log->buy_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];

        }
        if ($trade_log['sell_user_id']==$this->auth->id) {
            $type=1;
        }else{
            $type=0;
        } 

        return $this->view->fetch('',['info'=>$trade_log,'id'=>$id,'type'=>$type]);   

    }
       /**
     * 点对点交易  私下交易
     *
     * @ApiParams   (name="username", type="string", required=true, description="收款方用户名")
     * @ApiParams   (name="symbol", type="string", required=true, description="使用那个币汇款")
     * @ApiParams   (name="num", type="int", required=true, description="汇款的数量")
     * @return [type] [description]
     */
    public function pointToPoint()
    {   
      if ($this->request->isPost()) {

        $username = $this->request->post('username');
        $symbol = $this->request->post('symbol');
        $num = $this->request->post('num');
        $paypwd = $this->request->post('paypwd');
        Hook::listen("check_paypwd",$paypwd);
        
         $User = new User();
        $exists =$User->where('username', $username)->find();
        
        if (!$exists)
        {
            $this->error('收款方不存在');
        }
        if ($symbol=='0') {
           $this->error('请选择转账类型');
        }
        if ($this->auth->id == $exists->id) {
            $this->error('该地址不能转账');
        }
        $trade_min = config('site.trade_min');
        $trade_multiple = config('site.trade_multiple');
        if ($trade_min > $num) {
            $this->error('至少要转'.$trade_min);
        }

        if ($num % $trade_multiple != 0) {
            $this->error('请输入'.$trade_multiple.'的倍数');
        }

        $trade_poundage = config('site.trade_poundage');

        $poundage = $num*$trade_poundage/100;

        try {
            $token = $this->auth->getUserToken()[$symbol];
        } catch (\Exception $e) {
            $token = 0;
        }
        if ($num > $token+$poundage) {
            $this->error('余额不足');
        }

        User::tokenlog($symbol,$this->auth->id,$exists->id,-$num,'transfer-out','转账-转出');
        User::tokenlog($symbol,$this->auth->id,$exists->id,-$poundage,'transfer-poundage','转账-转出手续费');
        User::tokenlog($symbol,$exists->id,$this->auth->id,$num,'transfer-in','转账-转入');

        $this->success('转账成功');
      } 
       $trade_poundage = config('site.trade_poundage');
       $token = $this->auth->getUserToken();
       return $this->view->fetch('pointtopoint',['trade_poundage'=>$trade_poundage,'token'=>$token]); 
    }
        /**
     * 上传凭证
     * @return [type] [description]
     */
    public function voucher()
    {
        $image = $this->request->request('image/s',0);
        $id = $this->request->request('id/d',0);
        $tradelog = new Tradelog();
        $order = $tradelog->where('buy_user_id',$this->auth->id)->where('id',$id)->find();

        $rsp = $tradelog->where('id',$id)->update(['image'=>$image]);
        if ($rsp) {
            $this->success('上传成功');
        }else{
            $this->error('上传失败');
        }
        
    }
    // 支付信息
    public function paynote(){

       $id =$_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }

        $tradelog = new Tradelog();

        $trade_log = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)->where('id',$id)->find();

        $user_id = $this->auth->id;
        $userpay = Hook::listen("get_userpay",$user_id);
        $trade_log->pay = $userpay[0];


        $step1 =  config('site.trade_dispute_time_step1');
        $step2 =  config('site.trade_dispute_time_step2');

        if ( $trade_log->buy_user_id == $this->auth->id) {
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 0;
            }elseif($trade_log->status == 'affirm' && ($trade_log->updatetime + $step2*60 < time()) ){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }


            $user_id = $trade_log->sell_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];


        }elseif($trade_log->sell_user_id == $this->auth->id){
            if ($trade_log->status == 'waitting' && ($trade_log->createtime + $step1*60 < time())) {
                $trade_log->allowdispute = 1;
            }elseif($trade_log->status == 'affirm'){
                $trade_log->allowdispute = 1;
            }else{
                $trade_log->allowdispute = 0;
            }
            $user_id = $trade_log->buy_user_id;
            $touserpay = Hook::listen("get_userpay",$user_id);
            $trade_log->touserpay = $touserpay[0];

        }
        return $this->view->fetch('',['touserpay'=>$trade_log['touserpay']]); 
    }
     /**
     * 交易订单明细
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function tradeorderinfo()
    {
        $id =$_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }
        $trademodel = new TradeModel();
        $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        if (!$order) {
            $this->error('订单被外星人劫持');
        }

        $user_id = $this->auth->id;
        $userpay = Hook::listen("get_userpay",$user_id);
        $order->pay = $userpay[0];


        $tradelog = new Tradelog();

        $step1 =  config('site.trade_dispute_time_step1');
        $step2 =  config('site.trade_dispute_time_step2');
        switch ($order->action) {
            case 'sell':
                $tradelogs = $tradelog->where('sell_trade_id',$order->id)->select();
                foreach ($tradelogs as &$log) {
                    if ($log->status == 'waitting' && ($log->createtime + $step1*60 < time())) {
                        $log->allowdispute = 1;
                    }elseif($log->status == 'affirm'){
                        $log->allowdispute = 1;
                    }else{
                        $log->allowdispute = 0;
                    }

                    $user_id = $log->buy_user_id;
                    $touserpay = Hook::listen("get_userpay",$user_id);
                    $log->pay = $touserpay[0];

                }
                $order->tradelogs   =$tradelogs;
                break;
            case 'buy':
                $tradelogs = $tradelog->where('buy_trade_id',$order->id)->select();
                foreach ($tradelogs as &$log) {
                    if ($log->status == 'waitting' && ($log->createtime + $step1*60 < time())) {
                        $log->allowdispute = 0;
                    }elseif($log->status == 'affirm' && ($log->updatetime + $step2*60 < time()) ){
                        $log->allowdispute = 1;
                    }else{
                        $log->allowdispute = 0;
                    }
                    $user_id = $log->sell_user_id;
                    $touserpay = Hook::listen("get_userpay",$user_id);
                    $log->pay = $touserpay[0];

                }
                $order->tradelogs = $tradelogs;
                break;
            default:
                $this->error('您的订单数据异常，被外星人篡改了');
                break;
        }
       
        return $this->view->fetch('',['info'=>$order]); 
    }
    /**
     *会员充值接口
     * 
     * @ApiParams   (name="num", type="int", required=true, description="要充值的数量")
     * @ApiParams   (name="paypwd", type="string", required=true, description="安全密码")
     * TODO  如果USD改名成 则这里也要更改
     */
    public function moneyin()
    {    

            $trade_poundage = config('site.trade_poundage');
            // $rate = config('site.trade_exch_rate');
            $yb = db('coin')->where('symbol','USD')->find();
            $fae = db('coin')->where('symbol','FAE')->find();
            $trade_out_poundage = config('site.trade_out_poundage');
            $trade_in_poundage = config('site.trade_in_poundage');
           
          if ($this->request->isPost()) {
            $num = $this->request->post('num');
            $paypwd = $this->request->post('paypwd','');
            Hook::listen("check_paypwd",$paypwd);

            Hook::listen('check_pay');
            try {
                $token = $this->auth->getUserToken()['USD'];
            } catch (\Exception $e) {
                $token = 0;
            }
            // if ($num > $token) {
            //  $this->error('余额不足');
            // }
            // $coin = db('coin')->where('symbol','Y')->field('id,name,symbol,exch_rate,describe')->find();
            // 
            $trade_out_min = config('site.trade_out_min');
            $trade_out_multiple = config('site.trade_out_multiple');
            if ($trade_out_min > $num) {
                $this->error(__('不能少于'.$trade_out_min));
            }

            if ($num % $trade_out_multiple != 0) {
                $this->error(__('请输入'.$trade_out_multiple.'的倍数'));
            }

            $trademodel = new TradeModel();
            // $record = $trademodel->where('user_id',$this->auth->id)->where('symbol','USD')->where('tosymbol','USDT')->where('status','in',[0,1])->find();
            // if ($record) {
            //  $this->error('每人只能有一条委托购买的记录');
            // }
            $data = [
                'action' => 'buy',
                'user_id'   =>  $this->auth->id,
                'exch_rate' =>  1,
                'num'       =>  $num,
                'surplusnum'    =>  $num,
                'symbol'    =>  'USD',
                'tosymbol'  =>  'USDT',
                'pay'       =>  '$pay'
            ];
            $result = $trademodel->allowField(true)->validate('Trade.add')->save($data);
            if(false === $result){
                $this->error($trademodel->getError());
            }else{
                // User::tokenlog('USD',$this->auth->id,0,-$num,'buy','买入-充值');
                // TODO user 静态方法 扣除钱包 并写入记录
            }
            $this->success('委托购买成功');
           }
       return $this->view->fetch('',['rate'=>['USD'=>$yb['exch_rate'],'FAE'=>$fae['exch_rate']]]); 
    }
        /**
     * 自己寻找挂卖订单 使用 货币将另一种货币买下
     * symbol是买家卖出的 的货币  tosymbol 是卖家想要
     * @return [type] [description]
     */
    public function selfbuy()
    {
      if ($this->request->isPost()) {
        $id =$_GET['id'];
        $num = $this->request->post('num');
        if (!$id) {
            $this->error('请传入ID');
        }
        if (!$num) {
            $this->error('请传入买入数量');
        }
        $paypwd = $this->request->post('paypwd');
        Hook::listen("check_paypwd",$paypwd);
        // Hook::listen('check_pay');

        $trade_in_min = config('site.trade_in_min');
        $trade_in_multiple = config('site.trade_in_multiple');
        if ($trade_in_min > $num) {
            $this->error(__('不能少于'.$trade_in_min));
        }

        if ($num % $trade_in_multiple != 0) {
            $this->error(__('请输入'.$trade_in_multiple.'的倍数'));
        }

        $trademodel = new TradeModel();
        $trade = $trademodel->where('user_id','<>',$this->auth->id)->where('surplusnum','>',0)->where('id',$id)->where('action','sell')->find();

        if (!$trade) {
            $this->error('没有找到该订单');
        }
        if (!in_array($trade['status'], [0,1])) {
            $this->error('订单已经被人抢先一步了！');
        }

        if ($num > $trade['surplusnum']) {
            $this->error('数量不足，请刷新重试');
        }

        $trademodel->where('id',$trade->id)->dec('surplusnum',$num)->update(['status'=>1]);
        
        $userinfo =$this->auth->getUserinfo();
        $action = request()->action();
        $username = $userinfo['username'];
        $tradeno = Random::tradeno();
        Tradelog::Log($tradeno,$this->auth->id,$username,0,$trade->user_id,$trade->user->username,$trade->id,$num,$num,$num,'waitting',$action,$trade['symbol'],$trade['tosymbol']);

        $msg = "您订单号为{$tradeno}，买入USD{$num}个，订单已经匹配成功，请及时登录后台，查找卖方信息并及时转账。如您30分钟内没有转账系统将取消这笔订单。恶意操作，可能造成封号。";
        if ($userinfo['mobile']) {
            Smslib::notice($userinfo['mobile'],$msg);
        }

        $this->success('交易成功');
       }
        $id = $_GET['id'];

        $trademodel = new TradeModel();
        $trade = $trademodel
            ->where('symbol','USD')
            ->where('tosymbol','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('id',$id)
            ->find();
        $trade->user;
       return $this->view->fetch('',['info'=>$trade]); 
    }


    /**
     * 自己寻找挂买订单 使用 货币将另一种货币买下
     * symbol是买家卖出的 的货币  tosymbol 是卖家想要
     * @return [type] [description]
     */
    public function selfsell()
    {   
      if ($this->request->isPost()) {
        $id =$_GET['id'];
        $num = $this->request->post('num');
            if (!$id) {
                $this->error('请传入ID');
            }
            if (!$num) {
                $this->error('请传入卖出数量');
            }
            $paypwd = $this->request->post('paypwd');
            Hook::listen("check_paypwd",$paypwd);
            

            Hook::listen('check_pay');

            $trade_in_min = config('site.trade_in_min');
            $trade_in_multiple = config('site.trade_in_multiple');
            if ($trade_in_min > $num) {
                $this->error(__('不能少于'.$trade_in_min));
            }

            if ($num % $trade_in_multiple != 0) {
                $this->error(__('请输入'.$trade_in_multiple.'的倍数'));
            }


            $trademodel = new TradeModel();
            $trade = $trademodel->where('user_id','<>',$this->auth->id)->where('surplusnum','>',0)->where('id',$id)->where('action','buy')->find();
            if (!$trade) {
                $this->error('没有找到该订单');
            }
            if (!in_array($trade['status'], [0,1])) {
                $this->error('订单已经被人抢先一步了！');
            }

            if ($num > $trade['surplusnum']) {
                $this->error('数量不足，请刷新重试');
            }

            try {
                $token = $this->auth->getUserToken()['USD'];
            } catch (\Exception $e) {
                $token = 0;
            }

            $tradenum = bcmul($num, $trade['exch_rate'],2);
            if ($token < $tradenum) {
                $this->error('您的货币不足 '.$trade['symbol']);
            }

            User::tokenlog($trade['symbol'],$this->auth->id,0,-$tradenum,'selfsell','主动寻找买家卖出');
            $trade_out_poundage = config('site.trade_out_poundage');
            User::tokenlog('USD',$this->auth->id,0,-$tradenum*bcdiv($trade_out_poundage, 100,3),'sell_poundage','卖出扣除手续费');
            
            $trademodel->where('id',$trade->id)->dec('surplusnum',$num)->update(['status'=>1]);

            $action = request()->action();
            $username = $this->auth->getUserinfo()['username'];
            // Tradelog::Log(Random::tradeno(),$this->auth->id,$username,0,$trade->user_id,$trade->user->username,$trade->id,$num,$num,$num,'waitting',$action,$trade['symbol'],$trade['tosymbol']);
            $tradeno = Random::tradeno();
            Tradelog::Log($tradeno,$trade->user_id,$trade->user->username,$trade->id,$this->auth->id,$username,0,$num,$num,$num,'waitting',$action,$trade['symbol'],$trade['tosymbol']);
            $user_buy = User::get($trade->user_id);
            // var_dump($user_buy);

            if ($user_buy->mobile) {
                $msg = "您订单号为{$tradeno}，买入USD{$num}个，订单已经匹配成功，请及时登录后台，查找卖方信息并及时转账。如您30分钟内没有转账系统将取消这笔订单。恶意操作，可能造成封号。";

                Smslib::notice($user_buy->mobile,$msg);
            }


            $this->success('卖出成功');
             }
       $id = $_GET['id'];

        $trademodel = new TradeModel();
        $trade = $trademodel
            ->where('symbol','USD')
            ->where('tosymbol','USDT')
            ->where('surplusnum','>',0)
            ->where('status','in',[0,1])
            ->where('user_id','<>',$this->auth->id)
            ->where('id',$id)
            ->find();
        $trade->user;
        $trade_out_poundage = config('site.trade_out_poundage');
       return $this->view->fetch('',['info'=>$trade,'trade_out_poundage'=>$trade_out_poundage]); 
    }
    /**
     * 确认打款
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function comfirmdakuan()
    {
        $id = $_GET['id'];
        //$voucher = $this->request->request('voucher/s',0);
        if (!$id) {
            $this->error('订单id传入错误');
        }
        // if (!$voucher) {
        //     $this->error('请上传凭证');
        // }
        // $trademodel = new TradeModel();
        // $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        // if (!$order) {
        //     $this->error('订单被外星人劫持');
        // }

        $tradelog = new Tradelog();

        $order = $tradelog->where('buy_user_id',$this->auth->id)->where('id',$id)->find();
        
        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        
        if ($order->status != 'waitting') {
            $this->error('订单状态不正确');
        }
        
        $tradelog->save(['status'=>'affirm'],['id'=>$id]);
        $sell_user_id = $order['sell_user_id'];

        $userpay = Hook::listen("get_userpay",$sell_user_id);
        $config  = get_addon_config('clsms');
        $event = $config['event'];
        if (isset($event['comfirm'])) {
            $str = $event['comfirm'];
        }
        else {
            return false;
        }
        $str = str_replace('{tradeno}',$order['trade_no'],$str);
        $str = str_replace('{symbol}',$order['symbol'],$str);
        $msg = str_replace('{num}',$order['buy_num'],$str);
        if ($userpay[0]['mobile']) {
            Smslib::notice($userpay[0]['mobile'],$msg);
        }

        $this->success('确认打款');
    }

    /**
     * 确认收款
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function comfirmshoukuan()
    {
        $id = $_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }
        // $trademodel = new TradeModel();
        // $order = $trademodel->where('user_id',$this->auth->id)->where('id',$id)->find();
        // if (!$order) {
        //     $this->error('订单被外星人劫持');
        // }

        $tradelog = new Tradelog();

        $order = $tradelog->where('sell_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        if ($order->status != 'affirm') {
            $this->error('订单状态不正确');
        }

        $tradelog->where('id',$id)->update(['status'=>'finish']);

        $trademodel = new TradeModel();
        $buy_order = $trademodel->where('id',$order->buy_trade_id)->where('surplusnum',0)->find();

        $runningtradebuy = $tradelog->where('buy_trade_id',$order->buy_trade_id)->where('status','in',['waitting','affirm','dispute'])->find();
        if (!$runningtradebuy && $buy_order) {
            $trademodel->where('id',$order->buy_trade_id)->update(['status'=>'2']);
        }
        $runningtradesell = $tradelog->where('sell_trade_id',$order->sell_trade_id)->where('status','in',['waitting','affirm','dispute'])->find();
        $sell_order = $trademodel->where('id',$order->sell_trade_id)->where('surplusnum',0)->find();
        if (!$runningtradesell && $sell_order) {
            $trademodel->where('id',$order->sell_trade_id)->update(['status'=>'2']);
        }

        if ($order->symbol == 'USD' && $order->tosymbol == 'USDT') {
            User::tokenlog($order->symbol,$order->buy_user_id,0,$order->sell_num,'buy','买入到账');
        }
        if ($order->symbol == 'USD' && $order->tosymbol == 'FAE') {
            User::tokenlog($order->symbol,$order->buy_user_id,0,$order->sell_num,'buy','买入到账');
        }
        $this->success('确认收款');
    }
    /**
     * 申请订单仲裁
     * @param int $id 订单id
     * @return [type] [description]
     */
    public function dispute()
    {
        $id =$_GET['id'];
        if (!$id) {
            $this->error('订单id传入错误');
        }

        $tradelog = new Tradelog();

        $order = $tradelog->where('buy_user_id|sell_user_id',$this->auth->id)->where('id',$id)->find();

        if (!$order) {
            $this->error('订单被外星人劫持');
        }
        if ($order->status == 'waitting') {
            if($order->sell_user_id == $this->auth->id){
                $disputestatus =$order->status;
            }else{
                $this->error('您不能申请改订单的仲裁');
            }
            
        }elseif($order->status == 'affirm'){
            if ($order->buy_user_id == $this->auth->id) {
                $disputestatus =$order->status.'buy';
            }elseif($order->sell_user_id == $this->auth->id){
                $disputestatus =$order->status.'sell';
            }else{
                $this->error('订单被外星人劫持');
            }
        }else{
            $this->error('订单状态不允许申请仲裁');
        }
        $tradelog->save(['status'=>'dispute','disputestatus'=>$disputestatus],['id'=>$id]);
        $this->success('提交仲裁成功');
    } 


   
}
